// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', async () => {
    loading.show();
    try {
        const isConnected = await testApiConnection();
        if (!isConnected) {
            document.body.innerHTML = `
                <div class="connection-error">
                    <h2>无法连接到后端服务</h2>
                    <p>请确保后端服务已启动并且运行在正确的端口(8080)</p>
                    <button onclick="window.location.reload()">重试</button>
                </div>
            `;
            return;
        }
        
        // 如果连接成功，加载默认页面（宿舍楼管理）
        showSection('buildings');
    } catch (error) {
        Debug.error('初始化失败:', error);
        alert('系统初始化失败，请刷新页面重试');
    } finally {
        loading.hide();
    }
});

// 显示指定的section
function showSection(sectionId) {
    // 更新侧边栏激活状态
    document.querySelectorAll('.sidebar a').forEach(link => {
        link.classList.remove('active');
    });
    document.querySelector(`.sidebar a[onclick*="${sectionId}"]`).classList.add('active');

    // 隐藏所有section
    document.querySelectorAll('.section').forEach(section => {
        section.classList.add('hidden');
    });
    
    // 显示选中的section
    const currentSection = document.getElementById(sectionId);
    currentSection.classList.remove('hidden');

    // 加载对应的数据
    switch(sectionId) {
        case 'buildings':
            BuildingManager.loadBuildings();
            break;
        case 'rooms':
            RoomManager.loadBuildingSelect();
            break;
        case 'students':
            StudentManager.loadStudents();
            break;
        case 'hygiene':
            HygieneManager.loadBuildingSelect();
            break;
        case 'discipline':
            DisciplineManager.init();
            break;
    }
}

// 添加全局加载状态管理
const loading = {
    show() {
        document.body.classList.add('loading');
    },
    hide() {
        document.body.classList.remove('loading');
    }
};

// 加载宿舍楼选择框
async function loadBuildingSelect() {
    try {
        const buildings = await API.buildings.getAll();
        const buildingSelect = document.getElementById('buildingSelect');
        buildingSelect.innerHTML = '<option value="">选择宿舍楼</option>' +
            buildings.map(building => 
                `<option value="${building.id}">${building.buildingName}</option>`
            ).join('');
    } catch (error) {
        console.error('加载宿舍楼列表失败:', error);
        alert('加载宿舍楼列表失败');
    }
}

// 加载房间列表
async function loadRooms() {
    const buildingId = document.getElementById('buildingSelect').value;
    if (!buildingId) {
        document.getElementById('roomList').innerHTML = `
            <div class="empty-state">
                <p>请先选择宿舍楼</p>
            </div>
        `;
        return;
    }

    loading.show();
    try {
        const rooms = await API.rooms.getByBuilding(buildingId);
        const roomList = document.getElementById('roomList');
        
        if (!rooms || rooms.length === 0) {
            roomList.innerHTML = `
                <div class="empty-state">
                    <p>该宿舍楼暂无房间</p>
                    <button class="primary-btn" onclick="showAddRoomForm()">
                        <i class="icon add-icon"></i>添加房间
                    </button>
                </div>
            `;
            return;
        }

        roomList.innerHTML = rooms.map(room => `
            <div class="card">
                <h3>${room.roomNumber}</h3>
                <p>容量：${room.capacity}人</p>
                <p>当前入住：${room.currentOccupancy}人</p>
                <p class="text-muted">创建时间：${new Date(room.createdAt).toLocaleString()}</p>
                <div class="card-actions">
                    <button class="primary-btn" onclick="showRoomDetails(${room.id})">
                        <i class="icon student-icon"></i>查看学生
                    </button>
                    <button class="primary-btn" onclick="showHygieneRecords(${room.id})">
                        <i class="icon hygiene-icon"></i>卫生记录
                    </button>
                    <button class="danger-btn" onclick="deleteRoom(${room.id})">
                        <i class="icon delete-icon"></i>删除
                    </button>
                </div>
            </div>
        `).join('');
    } catch (error) {
        Debug.error('加载房间列表失败', error);
        document.getElementById('roomList').innerHTML = `
            <div class="error-state">
                <p>加载失败: ${error.message}</p>
                <button onclick="loadRooms()">重试</button>
            </div>
        `;
    } finally {
        loading.hide();
    }
}

// 显示添加房间表单
function showAddRoomForm() {
    const buildingId = document.getElementById('buildingSelect').value;
    if (!buildingId) {
        alert('请先选择宿舍楼');
        return;
    }
    document.getElementById('roomFormBuildingId').value = buildingId;
    document.getElementById('addRoomModal').classList.remove('hidden');
}

// 添加房间表单提交处理
document.getElementById('addRoomForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    const formData = new FormData(e.target);
    const room = {
        roomNumber: formData.get('roomNumber'),
        capacity: parseInt(formData.get('capacity')),
        currentOccupancy: 0,
        buildingId: parseInt(formData.get('buildingId'))
    };

    try {
        await API.rooms.create(room);
        hideModal('addRoomModal');
        loadRooms();
        e.target.reset();
    } catch (error) {
        console.error('添加房间失败:', error);
        alert('添加房间失败');
    }
});

// 加载卫生检查记录
async function loadHygieneRecords(roomId) {
    try {
        const records = await API.hygiene.getByRoom(roomId);
        const hygieneList = document.getElementById('hygieneList');
        hygieneList.innerHTML = records.map(record => `
            <div class="card">
                <h3>房间：${record.room.roomNumber}</h3>
                <p>评分：${record.score}</p>
                <p>检查时间：${new Date(record.checkTime).toLocaleString()}</p>
                <p>备注：${record.comments || '无'}</p>
                <div class="card-actions">
                    <button onclick="deleteHygieneRecord(${record.id})">删除</button>
                </div>
            </div>
        `).join('');
    } catch (error) {
        console.error('加载卫生检查记录失败:', error);
        alert('加载卫生检查记录失败');
    }
}

// 加载房间选择框（用于卫生检查）
async function loadRoomsForHygiene() {
    const buildingId = document.getElementById('hygieneBuilding').value;
    if (!buildingId) {
        document.getElementById('hygieneList').innerHTML = '';
        return;
    }

    try {
        const rooms = await API.rooms.getByBuilding(buildingId);
        const roomSelect = document.querySelector('#addHygieneForm select[name="roomId"]');
        roomSelect.innerHTML = '<option value="">请选择房间</option>' +
            rooms.map(room => 
                `<option value="${room.id}">${room.roomNumber}</option>`
            ).join('');
    } catch (error) {
        console.error('加载房间列表失败:', error);
        alert('加载房间列表失败');
    }
}

// 添加卫生检查记录
document.getElementById('addHygieneForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    const formData = new FormData(e.target);
    const record = {
        roomId: parseInt(formData.get('roomId')),
        score: parseInt(formData.get('score')),
        comments: formData.get('comments'),
        checkTime: new Date().toISOString()
    };

    try {
        await API.hygiene.create(record);
        hideModal('addHygieneModal');
        loadHygieneRecords(record.roomId);
        e.target.reset();
    } catch (error) {
        console.error('添加卫生检查记录失败:', error);
        alert('添加卫生检查记录失败');
    }
});

// 搜索学生
let searchTimeout;
async function searchStudent() {
    clearTimeout(searchTimeout);
    searchTimeout = setTimeout(async () => {
        const searchText = document.getElementById('studentSearch').value.trim();
        if (!searchText) return;

        try {
            const students = await API.students.getAll();
            const filtered = students.filter(student => 
                student.studentNumber.includes(searchText) || 
                student.name.includes(searchText)
            );
            
            const select = document.querySelector('#addDisciplineForm select[name="studentId"]');
            select.innerHTML = '<option value="">请选择学生</option>' +
                filtered.map(student => 
                    `<option value="${student.id}">${student.name} (${student.studentNumber})</option>`
                ).join('');
        } catch (error) {
            console.error('搜索学生失败:', error);
            alert('搜索学生失败');
        }
    }, 300);
}

// 添加违纪记录
document.getElementById('addDisciplineForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    const formData = new FormData(e.target);
    const record = {
        studentId: parseInt(formData.get('studentId')),
        description: formData.get('description'),
        recordTime: new Date().toISOString()
    };

    try {
        await API.discipline.create(record);
        hideModal('addDisciplineModal');
        loadDisciplinaryRecords(record.studentId);
        e.target.reset();
    } catch (error) {
        console.error('添加违纪记录失败:', error);
        alert('添加违纪记录失败');
    }
});

// 加载违纪记录
async function loadDisciplinaryRecords(studentId) {
    try {
        const records = await API.discipline.getByStudent(studentId);
        const disciplineList = document.getElementById('disciplineList');
        disciplineList.innerHTML = records.map(record => `
            <div class="card">
                <h3>${record.student.name}</h3>
                <p>学号：${record.student.studentNumber}</p>
                <p>违纪时间：${new Date(record.recordTime).toLocaleString()}</p>
                <p>描述：${record.description}</p>
                <div class="card-actions">
                    <button onclick="deleteDisciplinaryRecord(${record.id})">删除</button>
                </div>
            </div>
        `).join('');
    } catch (error) {
        console.error('加载违纪记录失败:', error);
        alert('加载违纪记录失败');
    }
}

// 添加错误处理函数
function handleApiError(error, message) {
    console.error(message, error);
    alert(message + '\n' + (error.message || '未知错误'));
}

// 测试API连接
async function testApiConnection() {
    try {
        Debug.log('测试API连接...');
        const response = await fetch('http://localhost:8080/api/test', {
            mode: 'cors',
            credentials: 'include',
            headers: {
                'Accept': 'application/json'
            }
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const data = await response.text();
        Debug.log('API测试结果:', data);
        return true;
    } catch (error) {
        Debug.error('API连接测试失败:', error);
        return false;
    }
}

// 显示房间详情（学生列表）
async function showRoomDetails(roomId) {
    const modal = document.createElement('div');
    modal.className = 'modal';
    modal.innerHTML = `
        <div class="modal-content">
            <h3>房间学生列表</h3>
            <div id="roomStudentList"></div>
            <div class="form-actions">
                <button onclick="this.closest('.modal').remove()">关闭</button>
            </div>
        </div>
    `;
    document.body.appendChild(modal);

    try {
        const students = await API.students.getByRoom(roomId);
        const studentList = document.getElementById('roomStudentList');
        
        if (!students || students.length === 0) {
            studentList.innerHTML = `
                <div class="empty-state">
                    <p>暂无学生入住</p>
                </div>
            `;
            return;
        }

        studentList.innerHTML = students.map(student => `
            <div class="list-item">
                <div class="student-info">
                    <h4>${student.name}</h4>
                    <p>学号：${student.studentNumber}</p>
                    <p>性别：${student.gender}</p>
                    <p>电话：${student.phone || '无'}</p>
                </div>
            </div>
        `).join('');
    } catch (error) {
        Debug.error('加载学生列表失败', error);
        document.getElementById('roomStudentList').innerHTML = `
            <div class="error-state">
                <p>加载失败: ${error.message}</p>
            </div>
        `;
    }
}

// 显示卫生记录
async function showHygieneRecords(roomId) {
    const modal = document.createElement('div');
    modal.className = 'modal';
    modal.innerHTML = `
        <div class="modal-content">
            <h3>卫生检查记录</h3>
            <div id="roomHygieneList"></div>
            <div class="form-actions">
                <button class="primary-btn" onclick="showAddHygieneForm(${roomId})">
                    <i class="icon add-icon"></i>添加记录
                </button>
                <button onclick="this.closest('.modal').remove()">关闭</button>
            </div>
        </div>
    `;
    document.body.appendChild(modal);

    try {
        const records = await API.hygiene.getByRoom(roomId);
        const hygieneList = document.getElementById('roomHygieneList');
        
        if (!records || records.length === 0) {
            hygieneList.innerHTML = `
                <div class="empty-state">
                    <p>暂无卫生检查记录</p>
                </div>
            `;
            return;
        }

        hygieneList.innerHTML = records.map(record => `
            <div class="list-item">
                <div class="hygiene-info">
                    <h4>检查时间：${new Date(record.checkTime).toLocaleString()}</h4>
                    <p>评分：${record.score}分</p>
                    <p>备注：${record.comments || '无'}</p>
                </div>
                <button class="danger-btn" onclick="deleteHygieneRecord(${record.id})">
                    <i class="icon delete-icon"></i>删除
                </button>
            </div>
        `).join('');
    } catch (error) {
        Debug.error('加载卫生记录失败', error);
        document.getElementById('roomHygieneList').innerHTML = `
            <div class="error-state">
                <p>加载失败: ${error.message}</p>
            </div>
        `;
    }
} 